package cn.vortex.device.web.servlet;

import cn.vortex.device.service.ApplyService;
import cn.vortex.device.service.CategoryService;
import cn.vortex.device.service.impl.ApplyServiceImpl;
import cn.vortex.device.service.impl.CategoryServiceImpl;
import cn.vortex.device.tool.GetDatetime;
import cn.vortex.device.tool.JdbcUtil;
import cn.vortex.device.tool.ResMessageBuilder;
import cn.vortex.device.vo.*;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet(name = "ApplyServlet", urlPatterns = "/apply/*")
public class ApplyServlet extends BaseServlet {

    private CategoryService categoryService = new CategoryServiceImpl();

    private ApplyService applyService = new ApplyServiceImpl();

    public ResMessage add(HttpServletRequest request, HttpServletResponse response) throws SQLException {

        //获取请求参数
        String level1 = request.getParameter("level1");//类别层级1
        String level2 = request.getParameter("level2");//类别层级2
        String level3 = request.getParameter("level3");//类别层级3
        String name = request.getParameter("name");//设备名称
        String count = request.getParameter("count");//设备数量
        String price = request.getParameter("price");//设备单价
        String applyPerson = request.getParameter("applyPerson");//申请人
        //String applyDate = request.getParameter("applyDate");//申请日期
        String applyDate = GetDatetime.getDatetime();
        String reason = request.getParameter("reason");//申请理由
        String specs = request.getParameter("specs");//设备规格
        //将请求参数封装为Apply对象
        Apply apply = new Apply();//创建Apply对象
        apply.setName(name);//初始化设备名称
        apply.setReason(reason);//初始化设备申请理由
        apply.setSpecs(specs);//初始化设备规格
        apply.setApplyPerson(applyPerson);//初始化申请人
        apply.setCateNum(level1 + "-" + level2 + "-" + level3);//初始化设备编号
        //声明返回信息对象
        ResMessage resMessage = null;

        try {
            JdbcUtil.startTransaction();//开始事务

            if (checkField(level3)) {//判断level3是否为空，为空返回false
                Category objById = categoryService.getObjById(Integer.parseInt(level3));
                apply.setCid(objById.getId());//初始化设备类别ID信息
                apply.setCategory(objById.getTitle());//初始化设备类别信息
            }
            if (checkField(count) && checkField(price)) {//判断count和price是否为空，为空返回false
                int c = Integer.parseInt(count);
                apply.setCount(c);//初始化设备数量
                double v = Double.parseDouble(price);
                apply.setPrice(v);//初始化设备单价
                apply.setAmount(v * c);//初始化设备总价值
            }



            if (checkField(applyDate)) {//判断applyDate是否为空，为空返回false
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = simpleDateFormat.parse(applyDate);//将日期格式转换为指定格式
                apply.setApplyDate(date);//初始化申请日期
            }

            if (applyService.addObj(apply)) {//调用applyService对象的addObj()方法将封装好的数据插入数据库，成功返回true
                resMessage = new ResMessage(200, "success", "申购单提交成功！");
            } else resMessage = new ResMessage(200, "fail", "申购单提交失败！");

        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtil.rollback();
            return new ResMessage(200, "fail", "系统错误！");
        } finally {
            JdbcUtil.commit();
        }

        return resMessage;
    }

    public ResMessage page(HttpServletRequest request, HttpServletResponse response) {

        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        String name = request.getParameter("name");
        String category = request.getParameter("category");
        String applyPerson = request.getParameter("applyPerson");
        String state = request.getParameter("state");
        Map<String, Object> params = new HashMap<>();
        if (checkField(name)) {
            params.put("name", name);
        }
        if (checkField(category)) {
            params.put("category", category);
        }
        if (checkField(applyPerson)) {
            params.put("applyPerson", applyPerson);
        }
        if (checkField(state)) {
            params.put("state", Integer.parseInt(state));
        }
        try {
            Object user = request.getSession().getAttribute("USER");
            PageVo<Apply> pageVo = null;
            if (user != null){//判断user 是否存在
                if (user instanceof User){//判断user是否是User的实例化对象，是返回true
                    User _user = (User) user;//将user转换为User对象
                    if (_user.getRoleId() == 1) {//判断用户的身份ID是否符合要求
                        //普通用户只能查看自己的申请信息
                        pageVo = applyService.pageObj(_user.getUsername(), page, limit, params);
                    } else if (_user.getRoleId() == 2){
                        //管理员可以查看所有人的申请信息
                        pageVo = applyService.pageObj(page, limit, params);
                    }
                }
                else {
                    throw new RuntimeException("传入的USER不符合要求！");//如果user对象不是User类的实例化对象抛出异常
                }
            } else {
                response.sendRedirect(request.getContextPath()+"/error/403.html");//不满足将请求转发至403错误页面
            }

            return new ResMessage(200, "success", pageVo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResMessage(200, "fail", "系统错误！");
        }

    }

    public ResMessage delete(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        ResMessage message = null;

        try {
            if (checkField(id)) {
                if (applyService.deleteObjById(Integer.parseInt(id))) {
                    message = new ResMessage(200,"success","删除成功");
                }else message = new ResMessage(200,"fail","删除失败");
            }else message = new ResMessage(200,"fail","参数非法");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResMessage(200,"fail","服务器错误！");
        }

        return message;
    }

    public ResMessage batchDelete(HttpServletRequest request, HttpServletResponse response) {

        String ids = request.getParameter("ids");
        Set<Integer> idSet = new HashSet<>();
        ResMessage message = null;
        try {
            if (checkField(ids)) {
                String[] split = ids.split(",");
                for (String s : split) {
                    idSet.add(Integer.parseInt(s));
                }
                if (applyService.deleteObjList(idSet)) {
                    message = new ResMessage(200,"success","删除成功");
                }else message = new ResMessage(200,"fail","删除失败");
            }else message = new ResMessage(200,"fail","参数非法");
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessageBuilder.resMessage(200,"fail","服务器错误");
        }

        return message;
    }

    public ResMessage edit(HttpServletRequest request, HttpServletResponse response) throws SQLException {

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String count = request.getParameter("count");
        String price = request.getParameter("price");
        String reason = request.getParameter("reason");
        String specs = request.getParameter("specs");
        String applyPerson = request.getParameter("applyPerson");
        String applyDate = request.getParameter("applyDate");


        Apply apply = new Apply();
        apply.setId(Integer.parseInt(id));
        apply.setName(name);
        apply.setReason(reason);
        apply.setSpecs(specs);
        apply.setApplyPerson(applyPerson);

        ResMessage resMessage = null;

        try {
            JdbcUtil.startTransaction();

            if (checkField(count) && checkField(price)) {
                int c = Integer.parseInt(count);
                apply.setCount(c);
                double v = Double.parseDouble(price);
                apply.setPrice(v);
                apply.setAmount(v * c);
            }

            if (checkField(applyDate)) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = simpleDateFormat.parse(applyDate);
                apply.setApplyDate(date);
            }

            if (applyService.updateApply(apply)) {
                resMessage = new ResMessage(200, "success", "申购单更新成功！");
            } else resMessage = new ResMessage(200, "fail", "申购单更新失败！");

        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtil.rollback();
            return new ResMessage(200, "fail", "系统错误！");
        } finally {
            JdbcUtil.commit();
        }

        return resMessage;
    }


    public ResMessage checkApply(HttpServletRequest request,HttpServletResponse response) throws SQLException {
        return getResMessage(request,1);
    }

    public ResMessage rejectApply(HttpServletRequest request,HttpServletResponse response) throws SQLException {
        return getResMessage(request,2);
    }

    private ResMessage getResMessage(HttpServletRequest request,Integer state) throws SQLException {
        String id = request.getParameter("id");
        String opinion = request.getParameter("opinion");
        //String checkDate = request.getParameter("checkDate");
        String checkDate = GetDatetime.getDatetime();
        String checkPerson = request.getParameter("checkPerson");

        ResMessage resMessage = null;
        try {
            JdbcUtil.startTransaction();
            if (checkField(id)){
                Apply objById = applyService.getObjById(Integer.parseInt(id));
                objById.setOpinion(opinion);
                System.out.println(checkDate);
                if (checkField(checkDate)){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = sdf.parse(checkDate);
                    //System.out.println(date);
                    objById.setCheckDate(date);
                }
                objById.setCheckPerson(checkPerson);
                objById.setState(state);
                if (applyService.updateObj(objById)) {
                    resMessage = ResMessageBuilder.resMessage(200,"success","操作成功");
                }else resMessage = ResMessageBuilder.resMessage(200,"fail","操作失败");
            }else resMessage = ResMessageBuilder.resMessage(200,"fail","参数非法");


        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtil.rollback();
            return new ResMessage(200,"fail","服务器错误");
        } finally {
            JdbcUtil.commit();
        }
        return resMessage;
    }

    boolean checkField(String field) {
        return field != null && !"".equals(field);
    }
}
